package com.jackaltsc.mydemodatastorage.externalstorage;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Environment;

public class ExternalTools {

    public static final String FILENAME = "FileTestByJackal.txt";


    public static void funExternalWrite(String data, String filename) {

        FileOutputStream fos = null;

        File file = new File(Environment.getExternalStorageDirectory(), filename);

        if (isExternalStorageWritable()) {

            try {

                fos = new FileOutputStream(file, true);
                fos.write(data.getBytes());

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static String funExternalRead(String filename) {

        FileInputStream fileInputStream = null;

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        File file = new File(Environment.getExternalStorageDirectory(), filename);

        if (isExternalStorageWritable()) {

            try {

                fileInputStream = new FileInputStream(file);
                int len = 0;
                byte[] data = new byte[1024];
                while ((len = fileInputStream.read(data)) != -1) {
                    byteArrayOutputStream.write(data, 0, len);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return new String(byteArrayOutputStream.toByteArray());
    }

    private static boolean isExternalStorageWritable() {

        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }
}
